import { defineStore } from 'pinia'
import { fetchAttrConfig } from '@/api/register'
import { fetchArticleList } from '@/api/app'
export const registerStore = defineStore('register', {
  unistorage: true, // 是否持久化到内存
  state: () => ({
    registerConf: {},
    registerForm: {}, //注册表单
    articleConf: {} // 文章内容相关
  }),
  actions: {
    setRegisterForm (data) {
      extend(this.registerForm, data)
    },

    getAttrConfig () {
      return new Promise((resolve, reject) => {
        if (this.registerConf?.car) {
          resolve(this.registerConf)
          return
        }
        fetchAttrConfig()
          .then(res => {
            this.registerConf = res
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
      })
    },

    getArticleConfig () {
      return new Promise((resolve, reject) => {
        const ks = Object.keys(this.articleConf)
        if (ks?.length) {
          resolve(this.articleConf)
          return
        }
        fetchArticleList()
          .then(res => {
            const { data } = res
            for (const key in data) {
              data[key].forEach(v => {
                if (v?.content) {
                  v.content = v?.content.replaceAll('\r\n\r\n', '<br>')
                  v.content = v?.content.replaceAll('↵↵', '<br>')
                }
              })
            }
            this.articleConf = data
            resolve(data)
          })
          .catch(err => {
            reject(err)
          })
      })
    }
  }
})

// 合并表单参数
function extend (target, source) {
  for (var k in source) {
    target[k] = source[k]
  }
  return target
}
